package jp.gr.java_conf.yuzu_project.parts;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import jp.gr.java_conf.yuzu_project.common.CommonUtil;
import jp.gr.java_conf.yuzu_project.common.SaveDataStock;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * データベースヘルパー用クラス.
 * @author ゆずプロジェクト
 *
 */
public class SQLiteHelper extends SQLiteOpenHelper {

	private static final String DB_NAME = "miniature_garden.db";
	private static final int DB_VER = 1;
	private String sql =
			 "create table "
			 + CommonUtil.TABLE_NAME
			 + " (_id  integer primary key autoincrement not null, "
			 + CommonUtil.SAVE_COLUMN
			 + " blob) ";
	
	public SQLiteHelper(Context context) {
		super(context, DB_NAME, null, DB_VER);
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {
		db.beginTransaction();
		try {
			db.execSQL(sql);
			
			ContentValues cv = new ContentValues();
			SaveDataStock stock = new SaveDataStock();

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			try {
				ObjectOutputStream oos = new ObjectOutputStream(baos);
				oos.writeObject(stock);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			byte[] value = baos.toByteArray();
			
			cv.put(CommonUtil.SAVE_COLUMN, value);
			for (int i = 0; i < CommonUtil.SAVE_TIMES; i++) {
				db.insert(CommonUtil.TABLE_NAME, null, cv);
			}
			
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
	}

	/*
	 * (non-Javadoc)
	 * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) {

	}

}
